import {Component, OnDestroy, OnInit} from '@angular/core';
import {TipService} from "../../main/services/tip.service";
import Common from '../../common/common';
import {ActivatedRoute, Router} from "@angular/router";
import {ExtendHttpService} from "../../common/extend-http.service";


@Component({
  selector: 'app-get-back-pwd',
  templateUrl: './get-back-pwd.component.html',
  styleUrls: ['./get-back-pwd.component.css']
})
export class GetBackPwdComponent implements OnInit, OnDestroy {
  isLoading = false;
  tipType = 'error';
  info = {mobile: '', code: ''};
  codeFlag = false;
  codeTime = 120;
  codeStr = '0s';
  intervalId = null;

  constructor(private tipService: TipService,
              private router: Router,
              private activatedRoute: ActivatedRoute,
              private extendHttp: ExtendHttpService) {
  }

  ngOnInit() {
  }

  // 获取验证码
  getCode() {
    if (!this.isLoading) {
      if (!this.info.mobile.trim()) {
        this.tipService.change(true, '请输入手机号');
        return;
      }
      if (!Common.mobileReg(this.info.mobile)) {
        this.tipService.change(true, '手机号格式不正确');
        return;
      }

      this.isLoading = !this.isLoading;
      this.extendHttp.post('/merchantApp/login/forgetPwd', {mobile: this.info.mobile}).subscribe(response => {
        let res = response.json();
        if (res.code == '0') {
          this.codeFlag = true;
          this.isLoading = !this.isLoading;
          this.intervalId = setInterval(() => {
            this.codeTime = this.codeTime - 1;

            if (this.codeTime === 0) {
              clearInterval(this.intervalId);
              this.codeTime = 120;
              this.codeFlag = false;
            }
            this.codeStr = this.codeTime + 's';
          }, 1000);
        } else {
          this.tipService.change(true, res['message']);
          this.isLoading = !this.isLoading;
        }
      }, error => {
        this.tipService.change(true, '系统繁忙，操作失败！');
        this.isLoading = !this.isLoading;
      });
    }
  }

  onSubmit() {
    if (!this.info.mobile.trim()) {
      this.tipService.change(true, '请输入手机号');
      return;
    }
    if (!Common.mobileReg(this.info.mobile)) {
      this.tipService.change(true, '手机号格式不正确');
      return;
    }
    if (!this.info.code.trim()) {
      this.tipService.change(true, '请输入获取到的验证码');
      return;
    }
    this.router.navigate(['/get-back-pwd2'], {queryParams: {mobile: this.info.mobile, code: this.info.code}});
  }

  ngOnDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

}
